import json
import os.path
import time

from django.conf import settings
from django.http import JsonResponse, StreamingHttpResponse
from django.views import View
from rest_framework import (viewsets, filters, )

from coder.models import Project, UserDefinedBlocklyBlock, CodeTemplate
from coder.paginations import BlocklyCodePagination, BlocklyFunctionCodePagination, GenerateTemplatePagination
from coder.serializers import BlocklyCodeSerializer, BlocklyFunctionCodeSerializer, GenerateTemplateSerializer
from ros_webdevtools_api.lib.save_code_file import save_code_file


class ProjectViewSet(viewsets.ModelViewSet):
    """
        Blockly项目代码
    """

    queryset = Project.objects.all()
    serializer_class = BlocklyCodeSerializer
    pagination_class = BlocklyCodePagination


class UserDefinedBlocklyBlockViewSet(viewsets.ModelViewSet):
    """
        Blockly自定义功能函数
    """

    queryset = UserDefinedBlocklyBlock.objects.all()
    serializer_class = BlocklyFunctionCodeSerializer
    pagination_class = BlocklyFunctionCodePagination


class CodeTemplateViewSet(viewsets.ModelViewSet):
    """
        代码模板
    """

    queryset = CodeTemplate.objects.all()
    serializer_class = GenerateTemplateSerializer
    pagination_class = GenerateTemplatePagination
    filter_backends = (filters.SearchFilter,)
    search_fields = ('template_name',)


class PanelInfoView(View):
    """
        面板信息
    """

    def get(self, request):
        data = {
            'templateCnt': CodeTemplate.objects.all().count(),
            'projectCnt': Project.objects.all().count(),
            'blocklyFunctionCnt': UserDefinedBlocklyBlock.objects.all().count()
        }

        return JsonResponse(data)


class GenerateCodeView(View):
    """
        根据模板生成代码
    """

    def get(self, request, timestamp):
        # 要打开的文件名称
        FILE_NAME = f'{timestamp}-{settings.GENERATE_FILE_NAME}'
        # 要打开文件的路径
        DIST_PATH = os.path.join(settings.BASE_DIR, 'generate_code', FILE_NAME)

        # 设置响应
        response = StreamingHttpResponse(open(DIST_PATH))
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = f'attachment;filename="{FILE_NAME}"'

        return response

    def post(self, request):
        # 当前时间戳
        TIME_STAMP = time.time()
        # 要保存的文件名称
        FILE_NAME = f'{TIME_STAMP}-{settings.GENERATE_FILE_NAME}'
        # 文件保存路径
        DIST_PATH = os.path.join(settings.BASE_DIR, 'generate_code', FILE_NAME)

        try:
            data = json.loads(request.body)
            code_template = CodeTemplate.objects.get(id=data['templateID'])

            if code_template is not None and 'code' in data:
                res = code_template.code.replace('{{ __CODE__ }}', data['code'])
                save_code_file(res, DIST_PATH)
                return JsonResponse({'timestamp': TIME_STAMP})

            return JsonResponse({})

        except Exception as e:
            print(e)
            return JsonResponse({})
